package com.xiaoyao.myframeapp.core;


import com.xiaoyao.myframeapp.FrameApplication;
import com.xiaoyao.myframeapp.mvp.http.PersistentCookieStore;
import com.xiaoyao.myframeapp.utils.L;
import com.xiaoyao.myframeapp.utils.NetworkUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author Administrator
 * @Author xiaoyao
 * @Email xiao80206040@qq.com
 * @Explain 对Retrofit2的基本设置
 * @date 2018/7/3 0003
 */
public class RetrofitFactory {

    private static final long TIMEOUT = 30;
    //设置 请求的缓存的大小跟位置
    private static File cacheFile = new File(FrameApplication.getmContext().getCacheDir(), "cache");
    private static Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb 缓存的大小




    // Retrofit是基于OkHttpClient的，可以创建一个OkHttpClient进行一些配置
    private static OkHttpClient httpClient = new OkHttpClient.Builder()
            //TODO 设置公共参数
            .addInterceptor(addQueryParameterInterceptor())
            //TODO 设置 token
            .addInterceptor(addHeaderInterceptor())
            //TODO 设置缓存 机制
            .addInterceptor(addCacheInterceptor())
            //TODO 添加一个log拦截器,打印所有的log  可以设置请求过滤的水平,body,basic,headers
            .addInterceptor( new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
//            // 增加一个拦截器 添加通用的Header
//            .addInterceptor(new Interceptor() {
//                @Override
//                public Response intercept(Chain chain) throws IOException {
//                    Request.Builder builder = chain.request().newBuilder();
//                    builder.addHeader("token", "123");
//                    return chain.proceed(builder.build());
//                }
//            })
            /*
            这里可以添加一个HttpLoggingInterceptor，因为Retrofit封装好了从Http请求到解析，
            出了bug很难找出来问题，添加HttpLoggingInterceptor拦截器方便调试接口
             */
            .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    L.e("RetrofitFactory:"+message);

                }
            }).setLevel(HttpLoggingInterceptor.Level.BASIC))
            //TODO 设置缓存 大小
            .cache(cache)
            //TODO 连接超时时间
            .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
            //TODO 读取超时时间
            .readTimeout(TIMEOUT, TimeUnit.SECONDS)
            //TODO 写入超时时间
//            .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
            //TODO Cookie缓存相关
            .cookieJar(new CookieJar() {
                private final PersistentCookieStore cookieStore = new PersistentCookieStore(FrameApplication.getmContext());

                //private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
                //Tip：key是String类型且为url的host部分
                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                    if (cookies != null && cookies.size() > 0) {
                        for (Cookie item : cookies) {
                            cookieStore.add(url, item);
                        }
                    }
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    List<Cookie> cookies = cookieStore.get(url);
                    return cookies != null ? cookies : new ArrayList<Cookie>();
                }
            })
            .build();

    private static RetrofitService retrofitService = new Retrofit.Builder()
            .baseUrl(UrlHelper.BASE_URL)
            //TODO 添加Gson转换器
            .addConverterFactory(GsonConverterFactory.create())
//            .addConverterFactory(JacksonConverterFactory.create())
            //TODO 添加Retrofit到RxJava的转换器
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(httpClient)
            .build()
            .create(RetrofitService.class);

    public static RetrofitService getInstance() {
        return retrofitService;
    }

    /**
     * 设置公共参数
     */
    private static Interceptor addQueryParameterInterceptor() {
        Interceptor addQueryParameterInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request request;
                HttpUrl modifiedUrl = originalRequest.url().newBuilder()
                        // Provide your custom parameter here
//                        .addQueryParameter("access_token", SpUtils.get("id", 0).toString() + "_" + SpUtils.get("token", "").toString())
                        .addQueryParameter("phoneSystem", "")
                        .build();
                request = originalRequest.newBuilder().url(modifiedUrl).build();
                return chain.proceed(request);
            }
        };
        return addQueryParameterInterceptor;
    }

    /**
     * 设置头
     */
    private static Interceptor addHeaderInterceptor() {
        Interceptor headerInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request.Builder requestBuilder = originalRequest.newBuilder()
                        // Provide your custom model_header here
//                        .header("token", SpUtils.get("token", "").toString())
                        .header("token", "token")
                        .method(originalRequest.method(), originalRequest.body());
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        };
        return headerInterceptor;
    }

    /**
     * 设置缓存 机制
     */
    private static Interceptor addCacheInterceptor() {
        Interceptor cacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!NetworkUtil.isNetworkAvailable(FrameApplication.getmContext())) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                Response response = chain.proceed(request);
                if (NetworkUtil.isNetworkAvailable(FrameApplication.getmContext())) {
                    int maxAge = 0;
                    // 有网络时 设置缓存超时时间0个小时 ,意思就是不读取缓存数据,只对get有用,post没有缓冲
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("Retrofit")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                            .build();
                } else {
                    // 无网络时，设置超时为4周  只对get有用,post没有缓冲
                    int maxStale = 60 * 60 * 24 * 28;
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" +
                                    maxStale)
                            .removeHeader("nyn")
                            .build();
                }
                return response;
            }
        };
        return cacheInterceptor;
    }

}

//        作者：Jaycee88
//        链接：https://www.jianshu.com/p/9674f6df910d
//        來源：简书
//        简书著作权归作者所有，任何形式的转载都请联系作者获得授权并注明出处。
